/**
 * axios 请求二次封装
 *
 **/
import axios from 'axios';
import {useUserInfo} from '../stores/userInfo'
import {useConfig} from "../stores/config";
import router from "../router";
// 根据运行环境获取基础请求URL
export const getUrl = (): string => {
    return 'https://demo.buildadmin.com'
}
const config = useConfig()
const http = axios.create({
    baseURL: getUrl(),
    timeout: 1000 * 10,
    headers: {
        'Content-Type': 'application/json',
        'think-lang': config.lang.defaultLang,
        server: true,
    },
    responseType: 'json',
    // withCredentials: true // 跨域请求使用凭证
});
const userInfo = useUserInfo()

// 请求拦截
http.interceptors.request.use(
    (config) => {
        // 携带token
        if (config.headers) {
            const token = userInfo.getToken()
            if (token) config.headers.batoken = token
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截
http.interceptors.response.use(
    (response) => {
        if (response.data && response.data.code !== 1) {
            if (response.data.code === 302) {
                router.push('/home')
            }
            // code不等于1, 页面then内的具体逻辑就不执行了
            return Promise.reject(response.data.msg)
        }
        return response
    },
    (error) => {
        if (error && error.response) {
            switch (error.response.status) {
                case 302:
                    error.message = '接口重定向了！';
                    break
                case 400:
                    error.message = '请求错误';
                    break;
                case 401:
                    error.message = '未授权，请登录';
                    break;
                case 403:
                    error.message = '拒绝访问';
                    break;
                case 404:
                    error.message = `请求地址出错: ${error.response.config.url}`;
                    break;
                case 408:
                    error.message = '请求超时';
                    break;
                case 500:
                    error.message = '服务器内部错误';
                    break;
                case 501:
                    error.message = '服务未实现';
                    break;
                case 502:
                    error.message = '网关错误';
                    break;
                case 503:
                    error.message = '服务不可用';
                    break;
                case 504:
                    error.message = '网关超时';
                    break;
                case 505:
                    error.message = 'HTTP版本不受支持';
                    break;
                default:
                    break;
            }
        } else {
            error.message = '网络错误，请稍后再试！';
        }
        const {response} = error
        if (response && response.data) {
            return Promise.reject(error)
        }
        const {message} = error
        console.error(message)
        return Promise.reject(error)
    }
)
export default {http}